from google.appengine.ext import webapp, db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users
import settings, models, cgi, logging
from django.utils import simplejson
from handlers.poi import POI

class MarkerInfoHandler(webapp.RequestHandler):
    def post(self):
        template_values = settings.base_template_data(self.request)
        poi_id = cgi.escape(self.request.get('id'))
        if poi_id:
            poi = db.get(db.Key.from_path('POI',long(poi_id)))
        else:
            poi = None
        if not(poi):
            template_values['poi'] = None
        elif poi.private and poi.user.user!=template_values['user']:
            template_values['unauth'] = True
        else:
            template_values['poi'] = poi
        path = settings.template_path('marker_info')
        self.response.out.write(template.render(path, template_values))

class MarkerFormHandler(webapp.RequestHandler):
    def post(self):
        template_values = settings.base_template_data(self.request)
        poi_id = cgi.escape(self.request.get('id'))
        if poi_id:
            poi = db.get(db.Key.from_path('POI',long(poi_id)))
        else:
            poi = None
        if not(poi):
            template_values['poi'] = None
        elif poi.user.user!=template_values['user']:
            template_values['unauth'] = True
        else:
            template_values['poi'] = poi
        path = settings.template_path('marker_form')
        self.response.out.write(template.render(path, template_values))

class MarkerSaveHandler(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-type'] = 'text/javascript; charset=utf-8'
        template_values = settings.base_template_data(self.request)
        poi_id = cgi.escape(self.request.get('id'))
        title = cgi.escape(self.request.get('title'))
        lat = cgi.escape(self.request.get('lat'))
        lon = cgi.escape(self.request.get('lon'))
        private = cgi.escape(self.request.get('private',''))
        d = None
        if not(title):
            d = {'error': "Error: Title required"}
        elif not(lat) or not(lon):
            d = {'error': "Position required"}
        elif private=='':
            d = {'error': "Error: Privacy required"}
        else:
            private = (private=='true')
            if poi_id:
                poi = db.get(db.Key.from_path('POI',long(poi_id)))
            else:
                poi = models.POI(title=title,private=private,lat_lng=db.GeoPt(lat,lon), user = template_values['local_user'])
            poi.title = title
            poi.lat_lng = db.GeoPt(lat,lon)
            poi.private  = private
            poi.desc1 = cgi.escape(self.request.get('desc1'))
            poi.desc2 = cgi.escape(self.request.get('desc2'))
            poi.desc3 = cgi.escape(self.request.get('desc3'))
            poi.put()
            d = POI(poi).get_dict()
        template_values['poi'] = poi
        d['old'] = bool(poi_id)
        d['html'] = template.render(settings.template_path('marker_info'), template_values)
        self.response.out.write(simplejson.dumps(d))

class MarkerDeleteHandler(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-type'] = 'text/javascript; charset=utf-8'
        template_values = settings.base_template_data(self.request)
        poi_id = cgi.escape(self.request.get('id'))
        if poi_id:
            poi = db.get(db.Key.from_path('POI',long(poi_id)))
        else:
            poi = None
        d = None
        if not(poi):
            d = {'error': "POI not found"}
        elif poi.user.user!=template_values['user']:
            d = {'error': "You are not authorized to delete this POI"}
        else:
            db.run_in_transaction(transact,poi)#db.delete(poi)
            d = {'sucess': True}
        self.response.out.write(simplejson.dumps(d))

application = webapp.WSGIApplication(
		[('/marker_form',MarkerFormHandler),
		('/save_marker',MarkerSaveHandler),
		('/delete_marker',MarkerDeleteHandler),
		('/marker_info',MarkerInfoHandler)],
		debug=settings.debug)

def main():
	run_wsgi_app(application)

if __name__=='__main__':
	main()
	

def transact(poi_delete):
    for comment in poi_delete.comments:
        db.delete(comment)
    db.delete(poi_delete)
